import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom';
import { Button, Icon } from 'components';
import ClickOutside from "./ClickOutside";
import styles from './index.less'

const modalRoot = document.body;


export default class Modal extends PureComponent {
  constructor(props) {
    super(props);
    this.el = document.createElement('div');
  }

  static defaultProps = {
    width: 570,
    visible: false,
    okType: 'primary',
    closable: true,
  };

  componentDidMount() {
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }

  saveRef = (name) => (node) => {
    this[name] = node;
  };

  getDialogElement = () => {
    const {
      okText,
      okType,
      cancelText,
      title,
      closable,
      children,
      onOk,
      onCancel,
      ...rest
    } = this.props;

    const header = (
      <div className={styles.header} ref={this.saveRef('header')}>
        {
          rest.header ? rest.header : (
            <div className={styles.title}>
              {title || '这里是标题'}
            </div>
          )
        }
      </div>
    );

    const footer = (
      <div className={styles.footer} ref={this.saveRef('footer')}>
        {rest.footer ? rest.footer : (
          <span>
          <Button type={okType || 'primary'} onClick={onOk}>
            {okText || 'Add Resources'}
          </Button>
          <Button type="danger" onClick={onCancel} style={{ marginLeft: '10px', paddingLeft: '40px', paddingRight: '40px'  }}>
            {cancelText || 'Cancel'}
          </Button>
        </span>
        )}
      </div>
    );

    let closer;
    if (closable) {
      closer = (
        <div
          onClick={onCancel}
          className={styles.close}
        >
          <Icon type="close" size="large" style={{ color: '#00B4CF' }} />
        </div>
      );
    }

    return (
      <div className={styles.content}>
        {closer}
        {header}
        <div className={styles.body}>
          {children}
        </div>
        {footer}
      </div>
    )
  };

  render() {
    const {
      visible,
      width,
      left,
      top,
    } = this.props;

    return (
      visible && ReactDOM.createPortal(
        (
          <div className={styles.mask}>
            <div className={styles.modal} style={{ width, left, top }}>
              <div className={styles.arrow} />
              <ClickOutside callback={this.props.onCancel}>
                {this.getDialogElement()}
              </ClickOutside>
            </div>
          </div>
        ),
        this.el,
      )
    )
  }
}

